package com.clarencezero.mylover.service.impl;

import com.clarencezero.mylover.mapper.ImageMapper;
import com.clarencezero.mylover.common.NumberUtil;
import com.clarencezero.mylover.common.QiNiuUtil;
import com.clarencezero.mylover.param.Result;
import com.clarencezero.mylover.param.entiry.ImageBean;
import com.clarencezero.mylover.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;


@Service("imageService")
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageMapper imageMapper;

    @Override
    public List<ImageBean> firstPage() {
        return imageMapper.getAllImage();
    }

    @Override
    public Result putImage(ImageBean bean) {
        Result result = new Result();
        int num = imageMapper.insertAImage(bean);
        if (num > 0) {
            result.success("疯疯同学上传照片成功");
        } else {
            result.failure("上传照片失败啦,重新上传吧!");
        }
        return result;
    }

    @Override
    public Result putImageByQiNiu(MultipartFile files, HttpServletRequest request) {
        String imagePathTemp = "E:\\myLoveData\\imageTemp\\";
        String qiNiuPath = "";
        String fileName = files.getOriginalFilename();
        String filePath = imagePathTemp + NumberUtil.getGuid() + ".jpg";
//        String filePath = request.getSession().getServletContext().getRealPath("/upload")+"\\"
//                + QiNiuUtil.renamePic(files.getOriginalFilename());
        System.out.println(files.getOriginalFilename());
        Result result = new Result();
        try {
            //保存至服务器
            File file=new File((filePath));
            files.transferTo(file);
            //上传七牛云服务器
            qiNiuPath = QiNiuUtil.qiniuUpload(filePath);
            if (qiNiuPath.contains("error")){
                result.failure();
                return result;
            }
            // 路径为文件且不为空则进行删除
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            ImageBean bean = new ImageBean();
            bean.setSrc(qiNiuPath);
            bean.setUserId("1");
            bean.setInfo("Shi is my girlfriend");
            // 插入表
            imageMapper.insertAImage(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
